package cn.yangtianxia.basic.interceptor;

import cn.yangtianxia.basic.annotation.PreAuthorize;
import cn.yangtianxia.basic.jwt.JwtUtils;
import cn.yangtianxia.basic.jwt.Payload;
import cn.yangtianxia.basic.jwt.RsaUtils;
import cn.yangtianxia.basic.jwt.UserInfo;
import cn.yangtianxia.system.mapper.PermissionMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;

    @Value("${jwt.rsa.pub}")
    private String jwtRsaPublic;//公钥的文件名字


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断有没有携带token
        String token = request.getHeader("U-TOKEN");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=UTF-8");
        if(!StringUtils.isEmpty(token)){
            //2.根据token 解密token得到登录人相关的所有信息
            PublicKey publicKey = RsaUtils
                    .getPublicKey((FileCopyUtils
                            .copyToByteArray(this.getClass().getClassLoader().getResourceAsStream(jwtRsaPublic))));
            Payload<UserInfo> infoFromToken = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            UserInfo userInfo = infoFromToken.getUserInfo();
            Object loginTmp = userInfo.getUser();//json格式的对象

           /* //2.根据token从redis获取登陆人信息
            Object loginTmp = redisTemplate.opsForValue().get(token);*/
            if(loginTmp != null){


                // 看是否是员工还是用户
                JSONObject logininfo = (JSONObject)loginTmp;

                if(logininfo.getInteger("type") == 0){//员工
                    //1.需要单独校验当前登录的员工，是否有权限访问当前资源
                    HandlerMethod method = (HandlerMethod) handler;
                    PreAuthorize preAuthorize = method.getMethodAnnotation(PreAuthorize.class);
                    if(preAuthorize != null){//当前这个方法打了注解，那么就需要校验权限，拥有权限，才能访问
                        //。获取当前请求的资源
                        String permissionSn = preAuthorize.value();
                        //。查询出当前登录人所拥有的资源权限
                        List<String> own = userInfo.getPermissions();
                        //。比对当前访问的资源是否包含在登录人所拥有的权限中
                        if(!own.contains(permissionSn)){
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"message\":\"noPermission\"}");
                            writer.flush();
                            writer.close();
                            return false;//阻止放行
                        }
                    }
                }
                //如果是用户，直接放行，不用校验权限
                //3.有，放行 刷新过期时间
//                redisTemplate.opsForValue().set(token,loginTmp,30, TimeUnit.MINUTES);
                return true;//放行
            }
        }
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;//阻止放行
    }
}
